//
//  CZtestRefresContro.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
enum TestRefreshState: Int {
	//下拉刷新
	case Nomal = 0
	//松手就刷新
	case Pulling = 1
	//正在刷新
	case Refreshing = 2
}
class CZtestRefresContro: UIControl {
	

	
	var currentScrollView: UIScrollView?
	var testRefreshState: TestRefreshState = .Nomal {
		didSet {
			switch testRefreshState {
			case .Nomal:
				print(".Nomale")
				//只有上一次是刷新状态,才去-=50
				if oldValue == .Refreshing {
					
					UIView.animateWithDuration(0.25, animations: {
						self.currentScrollView?.contentInset.top -= 50
					})
				}
				
			case .Pulling:
				print(".Pulling")
			case .Refreshing:
			
				UIView.animateWithDuration(0.25, animations: { 
					self.currentScrollView?.contentInset.top += 50
				})
			//告诉使用者要刷新数据
				sendActionsForControlEvents(.ValueChanged)
				
			}
		
		}
	
	
	}
	

	override init(frame: CGRect) {
		super.init(frame: frame)
		setUpUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}

	
	private func setUpUI() {
	backgroundColor = UIColor.yellowColor()
	
	}
	override func willMoveToSuperview(newSuperview: UIView?) {
		guard let scrollView = newSuperview as?  UIScrollView else {
		return
		}
		//添加 kvo 监听
		
		scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
		currentScrollView = scrollView
		frame.size.height = 50
		frame.size.width = currentScrollView!.frame.size.width
		frame.origin.y = -50
	}
	
	override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
		
//		print("test\(currentScrollView?.contentOffset.y ?? 0)")
		//拖动情况下自由两种状态 1.下拉刷新状态(Noml) 2.松手就刷新(Pulling)
		if currentScrollView!.dragging {
			//拖动
//		 print("1")
			let maxY = -(currentScrollView!.contentInset.top + 50)
//			print("临界点:\(maxY)")
			let contentOffSetY = currentScrollView!.contentOffset.y
			if contentOffSetY < maxY  && testRefreshState == .Nomal {
    //进入 pulling 状态
				testRefreshState = .Pulling
			} else if contentOffSetY >= maxY && testRefreshState == .Pulling {
			
			testRefreshState = .Nomal
				
			}
			
			//判断当前的偏移量和我们的 maxY 对比
			
			
			
		} else {
		//松手(refreshIng)
//		print("2")
			if testRefreshState == .Pulling {
    //正在刷新的状态
				testRefreshState = .Refreshing
			}
		}
		
		
		//要想进入正在刷新状态 1. 上一次是松手就刷新的状态,并且 还要松手
		
	}
	deinit {
	
	currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
		
	}

	
	
	func endRefesh() {
		testRefreshState = .Nomal
		
	}
	
}












